<?php
/**
 * 货币显示与转换助手
 */
class Helper_Currency{
     /**
	 * 货币转换
	 */
	static function conver($money,$from_code=null,$to_code=null,$precision=2){
	   if(strlen($to_code)<=0){
            $to_code=self::using();
        }
		if (strlen($from_code)<=0){
			$from_code =Q::ini('store/currency');
		}
	   return Store_Currencies::conver($money,$from_code,$to_code,$precision);
	}
	/**
	 * 货币显示
	 *
	 * @param float $amount  金额
	 * @param string $code   显示币种
	 * @param string $from_code 原始币种
	 * @param int $round 保留小数位数
	 * @return string
	 */
	static function fetch($amount,$from_code=null,$to_code = null,$round=2){
  	    if(strlen($to_code)<=0){
            $to_code=self::using();
        }
		if (strlen($from_code)<=0){
		    $from_code =$to_code;
			//$from_code =Q::ini('store/currency');
		}
		
		if ($to_code == $from_code){
			return self::_add_prefix_and_postfix(round($amount,$round),$to_code);
		}
		return self::_add_prefix_and_postfix(Store_Currencies::conver($amount,$from_code,$to_code,$round),$to_code);
	}
	/**
	 * 增加前缀后缀
	 *
	 * @param float $amount  金额
	 * @param string $code   币种
	 * @return string
	 */
	static function _add_prefix_and_postfix($amount,$code){
		static $_symbol;
		if(strlen($code)<=0){
            $code=Q::ini('currency');
        }
		switch(strtoupper($code)){
		    case 'JPY':
            case 'CNY':  return '&yen;'.$amount.' '.$code; break;
            case 'EUR':  return '&euro;'.$amount.' '.$code; break;
            case 'GBP':  return '&pound;'.$amount.' '.$code; break;
            case 'USD':  
            default:
                return '$'.$amount.' '.$code; break;
        }
	}
	/***
	 * 当前正在使用的  货币 
	 */
    static $_using;
	static function using(){
        if(!is_null(self::$_using)){
            return self::$_using;
        }elseif(isset($_SESSION['currency'][Q::ini('store/store_id')]) 
            &&strlen($_SESSION['currency'][Q::ini('store/store_id')])){
            self::$_using=$_SESSION['currency'][Q::ini('store/store_id')];
        }else{
            $_SESSION['currency'][Q::ini('store/store_id')]=Q::ini('store/currency');
            self::$_using=Q::ini('store/currency');
        }
        return self::$_using;
    }
    /**
     * 设置 使用 货币
     */         
    static function set($code=''){
        if(strlen($code)){
            do{
                if($code==self::using()){
                    break;
                }else{
                    $currency=Store_Currencies::used(Q::ini('store/store_id'),$code);
                    if($currency->isNewRecord()) break;
                    $_SESSION['currency'][Q::ini('store/store_id')]=$currency->code;
                    self::$_using=$currency->code;
                }
            }while(0);
        }
    }
}
